package com.dg11185.nearshop.activity.shop;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.nearshop.R;
import com.dg11185.libs.imageloader.core.DisplayImageOptions;
import com.dg11185.libs.imageloader.core.ImageLoader;
import com.dg11185.libs.imageloader.core.display.FadeInBitmapDisplayer;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.ormlite.android.apptools.OpenHelperManager;
import com.dg11185.libs.ormlite.dao.Dao;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.activity.user.LoginActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.DataCache;
import com.dg11185.nearshop.app.MyApplication;
import com.dg11185.nearshop.baidumap.EntityShopData;
import com.dg11185.nearshop.baidumap.MapConstant;
import com.dg11185.nearshop.baidumap.ShopPositionActivity;
import com.dg11185.nearshop.db.entity.Merchant;
import com.dg11185.nearshop.dbHelper.OrmLiteHelper;
import com.dg11185.nearshop.net.CacheConstant;
import com.dg11185.nearshop.net.NetCacheClient;
import com.dg11185.nearshop.net.entity.Area;
import com.dg11185.nearshop.net.entity.Comment;
import com.dg11185.nearshop.net.entity.Industry;
import com.dg11185.nearshop.net.entity.MerchantInfo;
import com.dg11185.nearshop.net.request.GeneralRequest;
import com.dg11185.nearshop.net.request.GetDayMerListRequest;
import com.dg11185.nearshop.net.request.GetMerchantCommentListRequest;
import com.dg11185.nearshop.net.request.GetMerchantInfoRequest;
import com.dg11185.nearshop.net.response.GetDayMerListResponse;
import com.dg11185.nearshop.net.response.GetDayMerListResponse.VipDaysShop;
import com.dg11185.nearshop.net.response.GetMerchantCommentListResponse;
import com.dg11185.nearshop.net.response.GetMerchantInfoResponse;
import com.dg11185.nearshop.net.response.LoginResponse;
import com.dg11185.nearshop.net.response.NetStatus;
import com.dg11185.nearshop.view.ErasedConflictListView;
import com.dg11185.nearshop.view.adapter.CommmentsAdapter;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.loading.BaseLoadLayout.LoadStateHandler;
import com.wlper.lib.view.loading.LoadLayoutWithFrameAnim;
import com.wlper.lib.view.loading.LoadLayoutWithTweenAnim;

/**
 * 
 * @author：Daibo
 * @time：2014-7-7 下午5:02:40
 */
public class ShopDetailActivity extends SubPageActivity implements OnClickListener {

    private final static int ACTIVITY_RESULT_COMMENT = 1;

    private final static int ACTIVITY_RESULT_LOGIN = 2;

    private boolean isDietShop = false; // 判断该店是否为餐饮行业

    private ImageView albumImage;

    private CheckBox btnLike, btnFavor;

    private TextView btnMoreComment, btnAddComment;

    private TextView txtName, txtDiscount, txtNameSmall, txtArea, txtIndustry, txtAddress, txtPhone;

    private int totalLike = 0, totalFavor = 0;

    private LoginResponse user = null;

    private String merchantId = "";

    private MerchantInfo merchantInfo = null;

    private DisplayImageOptions options = null;

    private LoadLayoutWithFrameAnim loadingView = null;

    /** 数据库 */
    private OrmLiteHelper databaseHelper = null;// 底包数据库helper

    /** 评论相关变量 */
    private ErasedConflictListView listView;

    private LinkedList<Comment> listDatas;

    private CommmentsAdapter listAdapter;

    private GetMerchantInfoRequest mInfoRequest = null;

    /** 相册帮助类 */
    private AlbumHelper albumHelper = null;

    private DBThread scanRecordThread = null;
    /***/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_detail);

        setSubPageTitle("商家详情");
        merchantId = getIntent().getStringExtra("merchant_id");
        Merchant merchant = getIntent().getParcelableExtra("merchant");
        scanRecordThread = new DBThread(merchant);
        scanRecordThread.start();
        
        user = MyApplication.getUser();
        options = new DisplayImageOptions.Builder().showStubImage(R.drawable.web_image_background).cacheOnDisc()
                .showImageOnFail(R.drawable.web_image_background).showImageForEmptyUri(R.drawable.web_image_background)
                .displayer(new FadeInBitmapDisplayer(1000)).resetViewBeforeLoading().build();
        mInfoRequest = new GetMerchantInfoRequest(merchantId);
        albumHelper = new AlbumHelper(this, merchantId);
        albumImage = (ImageView) this.findViewById(R.id.shop_detail_album);
        albumImage.setOnClickListener(this);

        listView = (ErasedConflictListView) this.findViewById(R.id.shop_detail_list);
        listDatas = new LinkedList<Comment>();
        listAdapter = new CommmentsAdapter(this, listDatas);
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (user == null) {
                    startActivityForResult(new Intent(ShopDetailActivity.this, LoginActivity.class),
                            ACTIVITY_RESULT_LOGIN);
                    return;
                }

                Intent intent = new Intent(ShopDetailActivity.this, ReplyCommentActivity.class);
                intent.putExtra("mainComment", listDatas.get(position));
                startActivity(intent);
            }
        });

        loadingView = (LoadLayoutWithFrameAnim) this.findViewById(R.id.shop_detail_loading_layout);
        loadingView.setStateHandler(stateHandler);
        loadingView.setTouchEventValid(true);
        findViewById(R.id.shop_detail_map_layout).setOnClickListener(this);
        btnLike = (CheckBox) this.findViewById(R.id.shop_detail_like);
        btnFavor = (CheckBox) this.findViewById(R.id.shop_detail_favor);
        btnMoreComment = (TextView) this.findViewById(R.id.shop_detail_mroe_comment);
        txtPhone = (TextView) this.findViewById(R.id.shop_detail_phone);
        btnAddComment = (TextView) this.findViewById(R.id.shop_detail_add_comment);
        btnLike.setOnClickListener(this);
        btnFavor.setOnClickListener(this);
        btnMoreComment.setOnClickListener(this);
        txtPhone.setOnClickListener(this);
        btnAddComment.setOnClickListener(this);

        txtName = (TextView) this.findViewById(R.id.shop_detail_name);
        txtDiscount = (TextView) this.findViewById(R.id.shop_detail_dicount);
        txtNameSmall = (TextView) this.findViewById(R.id.shop_detail_name_small);
        txtArea = (TextView) this.findViewById(R.id.shop_detail_area);
        txtIndustry = (TextView) this.findViewById(R.id.shop_detail_industry);
        txtAddress = (TextView) this.findViewById(R.id.shop_detail_address);
        initCommentData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        user = MyApplication.getUser();
        getShopInfo();
    }

    @Override
    public void onDestroy() {
        NetClient.httpCancel(this, true);
        /*
         * You'll need this in your class to release the helper when done.
         */
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }
        super.onDestroy();
    }

    private void getShopInfo() {
        final FrameLayout merchantLayout = (FrameLayout) findViewById(R.id.shop_detail_data_layout);
        loadingView.onLoading();
        merchantLayout.setVisibility(View.INVISIBLE);
        if (user != null) {
            mInfoRequest.getParams().remove("chshSign");
            mInfoRequest.add("userId", user.userId).encryption();
        } else {
            mInfoRequest.getParams().remove("chshSign");
            mInfoRequest.encryption();
        }
        mInfoRequest.setActionListener(new GetMerchantInfoRequest.ActionListener<GetMerchantInfoResponse>() {
            @Override
            public void onSuccess(GetMerchantInfoResponse result) {
                if (result.status == NetStatus.SUCCESS) {
                    merchantLayout.setVisibility(View.VISIBLE);
                    loadingView.onLoadSuccess();
                    merchantInfo = result.merchant;
                    initViewData();
                    initSpecialDay();
                } else {
                    onFailure(-1);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                loadingView.onLoadFailed();
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    loadingView.setLoadFailedHint(R.string.cant_connect_network);
                } else if (resultCode == -1) {
                    loadingView.setLoadFailedHint("服务器连接失败! ");
                }

            }
        });
        NetCacheClient.httpCacheGet(this, mInfoRequest);
    }

    private void initViewData() {
        if (merchantInfo != null) {

            merchantId = merchantInfo.merchantId;
            ImageLoader.getInstance().displayImage(merchantInfo.maxPhotoUrl, albumImage, options);
            txtName.setText(merchantInfo.merchantName);
            txtDiscount.setText(merchantInfo.preferential);

            if (!"".equals(merchantInfo.totalLikes)) {
                totalLike = Integer.parseInt(merchantInfo.totalLikes);
            }
            if (!"".equals(merchantInfo.totalFavors)) {
                totalFavor = Integer.parseInt(merchantInfo.totalFavors);
            }
            btnLike.setText(totalLike + "");
            btnFavor.setText(totalFavor + "");
            if (merchantInfo.isLike.equals("1")) {
                btnLike.setChecked(true);
            }

            if (merchantInfo.isFavor.equals("1")) {
                btnFavor.setChecked(true);
            }
            txtNameSmall.setText(merchantInfo.merchantName);
            try {
                Dao<Industry, Integer> industryDao = getHelper().getIndustryDao();
                Dao<Area, Integer> areaDao = getHelper().getAreaDao();
                List<Industry> industry = industryDao.queryForEq("industryId", merchantInfo.industryId);
                if (industry.size() > 0) {
                    txtIndustry.setText(industry.get(0).name);

                    if ("餐饮美食".equals(industryDao.queryForEq("industryId", industry.get(0).fatherId).get(0).name)) {
                        isDietShop = true;
                    }
                }
                List<Area> area = areaDao.queryForEq("areaNum", merchantInfo.areaNum);
                if (area.size() > 0) {
                    txtArea.setText(area.get(0).name);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            txtAddress.setText(merchantInfo.address);
            txtPhone.setText(merchantInfo.telephone);
        } else {

        }
    }

    private void initCommentData() {

        final LoadLayoutWithTweenAnim loadingView = (LoadLayoutWithTweenAnim) findViewById(R.id.shop_detail_comment_loading);
        final LinearLayout commentLayout = (LinearLayout) this.findViewById(R.id.shop_detail_comment_layout);
        loadingView.onLoading();
        loadingView.setLoadingHint("评论加载中..");
        final GetMerchantCommentListRequest request = new GetMerchantCommentListRequest(merchantId);
        request.add("pageNumber", "1").add("pageSize", "4").add("orderName", "createTime").encryption();

        request.setActionListener(new GetMerchantCommentListRequest.ActionListener<GetMerchantCommentListResponse>() {
            @Override
            public void onSuccess(GetMerchantCommentListResponse result) {
                if (result.status == NetStatus.SUCCESS) {
                    loadingView.onLoadSuccess();
                    if (Integer.parseInt(result.total) != 0) {
                        commentLayout.setVisibility(View.VISIBLE);
                        listDatas.clear();
                        listDatas.addAll(result.comments);
                        listAdapter.notifyDataSetChanged();
                        if (Integer.parseInt(result.total) <= 4) {
                            btnMoreComment.setVisibility(View.INVISIBLE);
                        } else {
                            btnMoreComment.setText("查看更多" + (Integer.parseInt(result.total) - 4) + "条评论");
                        }
                    }
                } else {
                    onFailure(-1);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                loadingView.onLoadFailed();
                commentLayout.setVisibility(View.INVISIBLE);
            }
        });
        NetClient.httpGet(this, request);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.shop_detail_map_layout:
            EntityShopData data = new EntityShopData(merchantInfo);
            Intent intent = new Intent(this, ShopPositionActivity.class);
            DataCache.setValue(MapConstant.dataShopInfoForMap, data);
            startActivity(intent);
            break;
        case R.id.shop_detail_album:
            albumHelper.showShopAlbum();
            break;
        case R.id.shop_detail_like:
            if (user == null) {
                startActivityForResult(new Intent(ShopDetailActivity.this, LoginActivity.class), ACTIVITY_RESULT_LOGIN);
                btnLike.setChecked(false);
                break;
            }
            if (btnLike.isChecked()) {
                userBehavior(GeneralRequest.LIKE);
                btnLike.setText(++totalLike + "");
            } else {
                userBehavior(GeneralRequest.CANCEL_LIKE);
                btnLike.setText(--totalLike + "");

            }
            break;
        case R.id.shop_detail_favor:
            if (user == null) {
                startActivityForResult(new Intent(ShopDetailActivity.this, LoginActivity.class), ACTIVITY_RESULT_LOGIN);
                btnFavor.setChecked(false);
                break;
            }
            if (btnFavor.isChecked()) {
                userBehavior(GeneralRequest.FAVOR);
                CacheConstant.deleteCacheFolder(Constants.getFavorList);
                btnFavor.setText(++totalFavor + "");
            } else {
                userBehavior(GeneralRequest.CANCEL_FAVOR);
                CacheConstant.deleteCacheFolder(Constants.getFavorList);
                btnFavor.setText(--totalFavor + "");
            }
            break;
        case R.id.shop_detail_phone:
            String phoneNum = txtPhone.getText().toString();// 得到电话号码
            Intent intentPhone = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum));
            this.startActivity(intentPhone);// 开始意图(及拨打电话)
            break;
        case R.id.shop_detail_mroe_comment:
            if (user == null) {
                startActivityForResult(new Intent(ShopDetailActivity.this, LoginActivity.class), ACTIVITY_RESULT_LOGIN);
                break;
            }
            Intent intent3 = new Intent(this, CommentListActivity.class);
            intent3.putExtra("merchantId", merchantId);
            startActivity(intent3);
            break;
        case R.id.shop_detail_add_comment:
            if (user == null) {
                startActivityForResult(new Intent(ShopDetailActivity.this, LoginActivity.class), ACTIVITY_RESULT_LOGIN);
                break;
            }
            Intent intent2 = new Intent(this, AddCommentsActivity.class);
            intent2.putExtra("isDietShop", isDietShop);
            intent2.putExtra("merchantId", merchantId);
            startActivityForResult(intent2, ACTIVITY_RESULT_COMMENT);
            break;
        default:
            break;
        }
    }

    /**
     * 
     * 用户行为提交，提交失败时提示用户并重新设置按钮状态
     */
    private void userBehavior(final String address) {
        GeneralRequest request = new GeneralRequest(address);
        request.add("merchantId", merchantInfo.merchantId).add("userId", user.userId).add("type", "1").encryption();

        request.setActionListener(new GeneralRequest.ActionListener<NetStatus>() {
            @Override
            public void onSuccess(NetStatus result) {
                if (NetStatus.SUCCESS != result) {
                    onFailure(1);
                } else {
                    CacheConstant.deleteCacheFile(mInfoRequest);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                if (address.equals(GeneralRequest.LIKE)) {
                    btnLike.setChecked(false);
                    btnLike.setText(--totalLike + "");
                } else if (address.equals(GeneralRequest.CANCEL_LIKE)) {
                    btnLike.setChecked(true);
                    btnLike.setText(++totalLike + "");
                } else if (address.equals(GeneralRequest.FAVOR)) {
                    btnFavor.setChecked(false);
                    btnFavor.setText(--totalFavor + "");
                } else if (address.equals(GeneralRequest.CANCEL_FAVOR)) {
                    btnFavor.setChecked(true);
                    btnFavor.setText(++totalFavor + "");
                }
                ViewUtils.showToast(ShopDetailActivity.this, "操作失败");
            }

        });
        NetClient.httpGet(this, request);
    }

    /**
     * You'll need this in your class to get the helper from the manager once
     * per class.
     */
    private OrmLiteHelper getHelper() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(this, OrmLiteHelper.class);
        }
        return databaseHelper;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (albumHelper.albumShow()) {
                albumHelper.hideShopAlbum();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
        case ACTIVITY_RESULT_COMMENT:
            initCommentData();
            break;
        case ACTIVITY_RESULT_LOGIN:
            break;
        default:
            break;
        }
    }

    private void initSpecialDay() {
        if (merchantInfo.isDayMer.equals("1")) {
            final LinearLayout layout = (LinearLayout) findViewById(R.id.shop_detail_vip_layout);
            final TextView content = (TextView) findViewById(R.id.shop_detail_vip_content);
            GetDayMerListRequest request = new GetDayMerListRequest().add(GetDayMerListRequest.MERCHANT_ID,
                    merchantInfo.merchantId).encryption();
            request.setActionListener(new GetDayMerListRequest.ActionListener<GetDayMerListResponse>() {
                @Override
                public void onSuccess(GetDayMerListResponse result) {
                    layout.setVisibility(View.VISIBLE);
                    if (result.dayMerList.size() > 0) {
                        String message = "";
                        for (VipDaysShop v : result.dayMerList) {
                            message = message + v.preferential + "\n";
                        }
                        content.setText(message);
                    }
                }

                @Override
                public void onFailure(int resultCode) {

                }
            });
            NetCacheClient.httpCacheGet(request);
        }
    }
  /** 将商家数据插入数据库，如果已经存在该商家，则先删除在插入 */
  private class DBThread extends Thread {
	  private Dao<Merchant, Integer> merchantDao = null;
      private Merchant merchant = null;

      public DBThread(Merchant merchant) {
          this.merchant = merchant;
          merchantDao = getHelper().getMerchantDao();
      }

      @Override
      public void run() {
          try {
              if (getHelper().isOpen()) {
                  if (merchantDao.countOf() > 10) {
                      merchantDao.delete(merchantDao.queryForFirst(merchantDao.queryBuilder().prepare()));
                  }
                  List<Merchant> merchantList = merchantDao.queryForEq("merchantId", merchant.merchantId);
                  if (merchantList.size() != 0) {
                      merchantDao.delete(merchantList);
                  }
                  merchantDao.create(merchant);
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }
    LoadStateHandler stateHandler = new LoadStateHandler() {

        @Override
        public void onReload() {
            getShopInfo();
        }

        @Override
        public void onLoading() {

        }

        @Override
        public void onLoadSuccess() {

        }

        @Override
        public void onLoadFailed() {

        }
    };
}
